package com.xoa.service.enterpriseTax.impl;

import com.xoa.dao.enterpriseTax.constructingUnit.ConstructingUnitMapper;
import com.xoa.model.enterpriseTax.constructingUnit.ConstructingUnit;
import com.xoa.service.enterpriseTax.ConstruingUnitService;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class ConstruingUnitServiceImpl implements ConstruingUnitService {
    @Autowired
    ConstructingUnitMapper constructingUnitMapper;
    @Override
    public ToJson<ConstructingUnit> selectAllConstruingUnit(boolean useFlag, Integer page, Integer limit, ConstructingUnit record) {
        ToJson<ConstructingUnit> toJson=new ToJson<ConstructingUnit>(1, "error");
        Map<String,Object> map=new HashMap<>();
        map.put("record", record);
        Integer integer = constructingUnitMapper.selectAllCount(map);
        toJson.setTotleNum(integer);
        PageParams pageParams=new PageParams();
        pageParams.setPageSize(limit);
        pageParams.setPage(page);
        pageParams.setUseFlag(true);
        map.put("PageParams", pageParams);
        List<ConstructingUnit> constructingUnits = constructingUnitMapper.selectAll(map);
        for (ConstructingUnit constructingUnit:constructingUnits){
            if (!StringUtils.checkNull(constructingUnit.getBranchOffice())){
                if ("0".equals(constructingUnit.getBranchOffice())){
                    constructingUnit.setBranchOffice("是");
                }else {
                    constructingUnit.setBranchOffice("否");
                }
            }
        }
        toJson.setObj(constructingUnits);
        toJson.setFlag(0);
        toJson.setMsg("OK");
        return toJson;
    }

    @Override
    public ToJson<ConstructingUnit> insertAllConstruingUnit(ConstructingUnit record) {
        ToJson<ConstructingUnit> toJson=new ToJson<ConstructingUnit>(1, "error");
        Map<String,Object> map=new HashMap<>();
        constructingUnitMapper.insert(record);
        toJson.setFlag(0);
        toJson.setMsg("OK");
        return toJson;
    }

    @Override
    public ToJson<ConstructingUnit> updateAllConstruingUnit(ConstructingUnit record) {
        ToJson<ConstructingUnit> toJson=new ToJson<ConstructingUnit>(1, "error");
        Map<String,Object> map=new HashMap<>();
        constructingUnitMapper.updateByPrimaryKey(record);
        toJson.setFlag(0);
        toJson.setMsg("OK");
        return toJson;
    }

    @Override
    public ToJson<ConstructingUnit> deleteAllConstruingUnit(Integer cuId) {
        ToJson<ConstructingUnit> toJson=new ToJson<ConstructingUnit>(1, "error");
        Map<String,Object> map=new HashMap<>();
        constructingUnitMapper.deleteByPrimaryKey(cuId);
        toJson.setFlag(0);
        toJson.setMsg("OK");
        return toJson;
    }


    @Override
    public ToJson<ConstructingUnit> uploadConstructingUnit(MultipartFile file,
                                                           HttpServletRequest request,
                                                           HttpServletResponse response,
                                                           HttpSession session) {
        ToJson<ConstructingUnit> toJson = new ToJson<>(1, "error");
        InputStream in = null;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            StringBuffer buffer = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                //sb=sb.append(rb.getString("upload.win"));
                //判断路径是否是相对路径，如果是的话，加上运行的路径
                String uploadPath = rb.getString("upload.win");
                if (uploadPath.indexOf(":") == -1) {
                    //获取运行时的路径
                    String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                    //获取截取后的路径
                    String str2 = "";
                    if (basePath.indexOf("/xoa") != -1) {
                        //获取字符串的长度
                        int length = basePath.length();
                        //返回指定字符在此字符串中第一次出现处的索引
                        int index = basePath.indexOf("/xoa");
                        //从指定位置开始到指定位置结束截取字符串
                        str2 = basePath.substring(0, index);
                    }
                    path = path.append(str2 + "/xoa");
                }
                path.append(uploadPath);
                buffer = buffer.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
                buffer = buffer.append(rb.getString("upload.linux"));
            }
            int success = 0;
            // 判断是否为空文件
            if (file.isEmpty()) {
                toJson.setMsg("请上传文件！");
                toJson.setFlag(1);
                return toJson;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
                    in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();

                    ConstructingUnit constructingUnit = null;
                    for (int i = 1; i <= lastRowNum; i++) {
                        constructingUnit = new ConstructingUnit();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            // 建设单位名称
                                            cell.setCellType(CellType.STRING);
                                            if (cell.getStringCellValue() != null) {
                                                constructingUnit.setCuName(cell.getStringCellValue());
                                            }
                                            break;
                                        case 1:
                                            //建设单位社会信用代码
                                            cell.setCellType(CellType.STRING);
                                            if (cell.getStringCellValue() != null) {
                                                constructingUnit.setCuCode(cell.getStringCellValue());
                                            }
                                            break;
                                        case 2:
                                            //工程名称
                                            cell.setCellType(CellType.STRING);
                                            if (cell.getStringCellValue() != null) {
                                                constructingUnit.setProjectName(cell.getStringCellValue());
                                            }
                                            break;
                                        case 3:
                                            //建设地址
                                            cell.setCellType(CellType.STRING);
                                            if (cell.getStringCellValue() != null) {
                                                constructingUnit.setConstructionAddress(cell.getStringCellValue());
                                            }
                                            break;
                                        case 4:
                                            //合同金额(万元)
                                            cell.setCellType(CellType.STRING);
                                            if (cell.getStringCellValue() != null) {
                                                constructingUnit.setAmount(cell.getStringCellValue());
                                            }
                                            break;
                                        case 5:
                                            // 开工日期
                                            if (cell.getDateCellValue() != null) {
                                                String anString = "";
                                                anString = new SimpleDateFormat("yyyy/MM/dd").format(cell.getDateCellValue());
                                                SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
                                                Date date = sf.parse(anString);
                                                constructingUnit.setCommencementDate(date);
                                            }
                                            break;
                                        case 6:
                                            // 竣工日期
                                            if (cell.getDateCellValue() != null) {
                                                String anString = "";
                                                anString = new SimpleDateFormat("yyyy/MM/dd").format(cell.getDateCellValue());
                                                SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
                                                Date date = sf.parse(anString);
                                                constructingUnit.setCompletionDate(date);
                                            }
                                            break;
                                        case 7:
                                            // 施工单位名称
                                            cell.setCellType(CellType.STRING);
                                            if (cell.getStringCellValue() != null) {
                                                constructingUnit.setConstructionUnitName(cell.getStringCellValue());
                                            }
                                            break;
                                        case 8:
                                            // 建设单位社会信用代码
                                            cell.setCellType(CellType.STRING);
                                            if (cell.getStringCellValue() != null) {
                                                constructingUnit.setConstructionUnitCode(cell.getStringCellValue());
                                            }
                                            break;
                                        case 9:
                                            // 施工单位属地
                                            cell.setCellType(CellType.STRING);
                                            if (cell.getStringCellValue() != null) {
                                                constructingUnit.setConstructionUnitPossession(cell.getStringCellValue());
                                            }
                                            break;
                                        case 10:
                                            // 是否在区内开设分公司(0-是,1-否)
                                            cell.setCellType(CellType.STRING);
                                            if (cell.getStringCellValue() != null) {
                                                if (cell.getStringCellValue().equals("是")){
                                                    constructingUnit.setBranchOffice(0+"");
                                                }else if(cell.getStringCellValue().equals("否")){
                                                    constructingUnit.setBranchOffice(1+"");
                                                }
                                            }
                                            break;
                                        case 11:
                                            // 经纬度
                                            cell.setCellType(CellType.STRING);
                                            if (cell.getStringCellValue() != null) {
                                                constructingUnit.setLongitude(cell.getStringCellValue());
                                            }
                                            break;
                                        case 12:
                                            //备注
                                            cell.setCellType(CellType.STRING);
                                            if (cell.getStringCellValue() != null) {
                                                constructingUnit.setRemark(cell.getStringCellValue());
                                            }
                                            break;
                                        case 13:
                                            //报送单位
                                            cell.setCellType(CellType.STRING);
                                            if (cell.getStringCellValue() != null) {
                                                constructingUnit.setReportingUnit(cell.getStringCellValue());
                                            }
                                            break;
                                    }
                                }
                            }
                            if (constructingUnit != null) {
                                int a = constructingUnitMapper.insertSelective(constructingUnit);
                                if (a != 0) {
                                    success++;
                                }
                            }
                        }
                    }
                }
            }
            ConstructingUnit temp = new ConstructingUnit();
            toJson.setFlag(0);
            toJson.setMsg("ok");
            toJson.setObject(temp);
            toJson.setTotleNum(success);
        } catch (Exception e) {
            e.printStackTrace();
            toJson.setMsg("数据保存异常");
            toJson.setFlag(1);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return toJson;
    }


    public ToJson<ConstructingUnit> selectAllConstruingUnit2() {
        ToJson<ConstructingUnit> toJson=new ToJson<ConstructingUnit>(1, "error");
        Map<String,Object> map=new HashMap<>();
        ConstructingUnit constructingUnit2=new ConstructingUnit();
        map.put("record",constructingUnit2);
        List<ConstructingUnit> constructingUnits = constructingUnitMapper.selectAll(map);
        for (ConstructingUnit constructingUnit:constructingUnits){
            if (!StringUtils.checkNull(constructingUnit.getBranchOffice())){
                if ("0".equals(constructingUnit.getBranchOffice())){
                    constructingUnit.setBranchOffice("是");
                }else {
                    constructingUnit.setBranchOffice("否");
                }
            }
        }
        toJson.setObj(constructingUnits);
        toJson.setFlag(0);
        toJson.setMsg("OK");
        return toJson;
    }


}
